
const express = require("express");
const router = express.Router();
const multer = require("multer");
const path = require("path");

function suiJiShu(min, max) {
    const dec = max - min;
    return parseInt(Math.random() * dec + min);
}
//作者：段彦蓉
//创建存储对象
const storage = multer.diskStorage({
    destination: path.join(__dirname, "../public/upload"),
    filename: function (req, file, cb) {
        const name = Date.now() + "" + suiJiShu(100000, 10000000)+path.extname(file.originalname);
        cb(null,name)
    }
})

//作者：段彦蓉
const upload = multer({//配置上传处理
    storage,
    fileFilter: function (req, file, cb) {
        //如何得到文件名的后缀名
        const ext = path.extname(file.originalname).toLowerCase();//得到文件的后缀名
        const expects = [".jpg", ".png", ".bmp", ".gif", ".tiff"];//服务器允许的后缀名
        if (expects.includes(ext)) {
            cb(null, true);
        } else {
            cb(new Error("文件类型不正确"));
        }
    },
    limits: {
        fileSize: 500 * 1024//文件限制在500kb以内
    }
}).array("image");

router.post("/", (req, res) => {
    upload(req, res, function (err) {
        if (err) {
            //发生错误
            res.send({
                code: 1,
                message: err.message
            })
        } else {
            //一切都好
            res.send({
                code:0,
                message:"",
                data:req.files.map(item=>"/upload/"+item.filename)
            });
        }
    })
})


module.exports = router;
